package edu.unh.sustain;

import java.util.Calendar;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.Spinner;
import android.widget.Toast;

public class UtilMenuActivity extends Activity {
	private static final int GET_CODE = 0;
	private ProgressDialog pd;
	private Calendar cal = Calendar.getInstance();
	private int cDay;
	private int cMonth;
	private int cYear;
	private Bundle extras;
	private Button b1;
	private Button b2;
	private Spinner s;
	private DatePicker dp;
	private Intent intentList, intentChart;
	private String buttonText;
	private String id;
	private String array_spinner[];
	private UtilityChartActivity chart;
	private ConnectivityManager cm;
	private NetworkInfo netInfo;
	
	// date picker on change handler
	DatePicker.OnDateChangedListener dcl = new DatePicker.OnDateChangedListener() {
		public void onDateChanged(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			
			if(year < 2008)
			{
				cal.set(Calendar.YEAR, 2008);
				dp.updateDate(2008, monthOfYear, dayOfMonth);
			} else if(year >= cYear) {
				cal.set(Calendar.YEAR, cYear);
				dp.updateDate(cYear, monthOfYear, dayOfMonth);
				if(monthOfYear >= cMonth) {
					cal.set(Calendar.MONTH, cMonth);
					dp.updateDate(cYear, cMonth, dayOfMonth);
					if(dayOfMonth >= cDay) {
						cal.set(Calendar.DAY_OF_MONTH, cDay);
						dp.updateDate(cYear, cMonth, cDay);
					}
				}
			}
			else
				cal.set(Calendar.YEAR, year);
			
			cal.set(Calendar.MONTH, monthOfYear);
			cal.set(Calendar.DAY_OF_MONTH, dayOfMonth);
		}
	};
	
	/*********************************************************************************/
	/********************** DECLARATIONS END *****************************************/
	/*********************************************************************************/
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		ArrayAdapter<String> aa;
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.energy_menu); 
		
		id = null;
		
		// set up intent that is used on return
		intentList = new Intent();
		intentList.setClass(this, BuildingListActivity.class);
		
		chart = new UtilityChartActivity();
		//intentChart = chart.execute(this);
		
		// set up display spinner
		array_spinner = new String[4];
		array_spinner[0] = "Day";
		array_spinner[1] = "Week";
		array_spinner[2] = "Month";
		array_spinner[3] = "Year";
		
		// save date info for graph max
		cYear = cal.get(Calendar.YEAR);
		cMonth = cal.get(Calendar.MONTH);
		cDay = cal.get(Calendar.DAY_OF_MONTH) - 1; // newest data is yesterday
		
		// set up date picker
		dp = (DatePicker)findViewById(R.id.datePicker);
		dp.init(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH) - 1, dcl);
		
		// set up time period spinner
		s = (Spinner)findViewById(R.id.time_select);
		aa = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, array_spinner);
		aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		s.setAdapter(aa);
		s.setPrompt("Choose a timespan");
		
		// set up building picker button
		b1 = (Button)findViewById(R.id.buildingButton);
		b1.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
				netInfo = cm.getActiveNetworkInfo();
				if(netInfo != null && netInfo.isConnected())
				{
					startActivityForResult(intentList, GET_CODE);
				} else {
					Toast alert = Toast.makeText(UtilMenuActivity.this, "No data connection is available", 
							Toast.LENGTH_LONG);
					alert.show();
				}
			}
		});
		
		// set up utility display button
		b2 = (Button)findViewById(R.id.displayButton);
		b2.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
				netInfo = cm.getActiveNetworkInfo();
				if(netInfo != null && netInfo.isConnectedOrConnecting())
				{
					if(id != null)
					{
						pd = ProgressDialog.show(UtilMenuActivity.this,"Please wait","Retrieving data",true,false,null);
	
						new Thread() 
						{
						  public void run() 
						  {
						     try
						       {
						    	chart.setBuildingId(id);
								chart.setDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH) + 1, cal.get(Calendar.DAY_OF_MONTH),
												s.getSelectedItem().toString());
								chart.setName(extras.getString("building_name"));
								intentChart = chart.execute(UtilMenuActivity.this);
						      } catch (Exception e) {
							        //Log.e("tag",e.getMessage());
							  }
						     pd.dismiss();
						     startActivity(intentChart);
						  }
						}.start();
					} else {
						Toast alert = Toast.makeText(UtilMenuActivity.this, "Please select a building first", 
														Toast.LENGTH_LONG);
						alert.show();
					}
				} else {
					Toast alert = Toast.makeText(UtilMenuActivity.this, "No data connection is available", 
							Toast.LENGTH_LONG);
					alert.show();
				}
			}
		});
	}
	
	
	// handles getting the result from calling the building list activity
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(data != null)
		{
			super.onActivityResult(requestCode, resultCode, data);
			extras = data.getExtras();
			
			// grab the selected building name from the intent extras
			buttonText = extras.getString("building_name");
			id = extras.getString("building_id");
			b1.setText(buttonText);
		}
	}
}
